
<template>
  <div class="app-container">
    <el-form ref="queryForm" :inline="true" :model="formUser" size="small">
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="formUser.userName" placeholder="用户名称" />
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select v-model="formUser.status" placeholder="用户状态">
          <el-option
            v-for="(item,index) in dict.dict.switch"
            :key="index"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getUserInfo()">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetInfo('queryForm')">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="it1">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="insertUserInfo"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      tooltip-effect="dark"
      :stripe="true"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="用户编号" type="index" width="120" />
      <el-table-column prop="userName" label="用户名称" width="120" />
      <el-table-column prop="nikeName" label="用户昵称" show-overflow-tooltip width="120" />
      <el-table-column prop="phone" label="手机号" width="120" />
      <el-table-column prop="sex" label="性别" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.dict.sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column key="status" prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :disabled="scope.row.id === '9bcfceac5b8311ed9feb525400cfb560' ? true:false"
            :active-value="0"
            :inactive-value="1"
            @change="switchStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        width="150"
        show-overflow-tooltip
      >
        <template slot-scope="scope">{{ scope.row.createTime }}</template>
      </el-table-column>

      <el-table-column
        label="操作"
        min-width="250"
        align="center"
      >
        <template v-if="scope.row.id !== '9bcfceac5b8311ed9feb525400cfb560'" slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            icon="el-icon-edit"
            @click="updateUserInfo(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-key"
            @click="restPassWord(scope.row)"
          >重置</el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="delUserInfo(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="formUser.pageIndex"
      :limit.sync="formUser.pageSize"
      @pagination="getUserInfo"
    />

    <!-- 新增及修改 -->
    <el-dialog :title="title" :visible.sync="dialogFormInsertUpdate" width="570px" append-to-body :close-on-click-modal="false">
      <el-form ref="formInfo" :model="form" size="small" :rules="rules" :inline="true" label-width="70px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="昵称" prop="nikeName">
          <el-input v-model="form.nikeName" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="密码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>

        <el-form-item label="性别" style="width: 250px">
          <el-radio-group v-model="form.sex">
            <el-radio
              v-for="dict in dict.dict.sex"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.dict.switch"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" style="margin-bottom: 0;">
          <el-select v-model="form.roleIds" multiple style="width: 437px" placeholder="请选择角色">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitFrom">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { pageUserInfo, userSave, updatePassWord, selectUser, delUserInfo, editUserStatus } from '@/api/system/user'
import { validEmail } from '@/utils/validate'
export default ({
  name: 'User',
  dicts: ['sex', 'switch'],
  data() {
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 5, max: 30, message: '长度在5到30个字符' }
        ],
        nikeName: [
          { required: true, message: '请输入昵称', trigger: 'blur' }

        ],
        email: [
          { required: true, trigger: 'blur', validator: validateEmail }
        ]
      },
      // 表单参数
      formUser: {
        userName: '',
        status: '',
        pageIndex: 1,
        pageSize: 10
      },
      // 数据总条数
      total: 0,
      // 下拉选择
      options: [],
      // 表格数据值
      tableData: [],
      // DigLog 弹框控制
      dialogFormInsertUpdate: false,
      // DigLog 标题
      title: '',
      // 清空表单
      form: {
      },
      // 是否是新增或修改
      insertOrEdit: false
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    // 查询用户信息操作
    getUserInfo() {
      pageUserInfo(this.formUser).then(response => {
        this.tableData = response.data.dataInfo
        this.total = response.data.total
      })
    },
    // 重置信息
    resetInfo(queryForm) {
      this.resetForm(queryForm)
    },
    // 清空表单
    restForms() {
      this.form = {
        userName: undefined,
        nikeName: undefined,
        email: undefined,
        sex: 0,
        status: 0,
        password: undefined
      }
      this.resetForm('formInfo')
    },
    // 点击修改
    updateUserInfo(row) {
      selectUser(row.id).then(response => {
        this.form = response.data
        this.form.roleIds = response.data.roleIds
        this.options = response.data.roles
        this.insertOrEdit = true
        this.title = '修改信息'
        this.dialogFormInsertUpdate = true
      })
    },
    // 点击新增
    insertUserInfo() {
      this.restForms()
      selectUser().then(response => {
        this.options = response.data.roles
        this.title = '新增信息'
        this.dialogFormInsertUpdate = true
      })
    },
    // 取消操作
    cancel() {
      this.restForms()
      this.dialogFormInsertUpdate = false
    },
    // 重置密码操作
    restPassWord(row) {
      this.$prompt('请输入新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false
      }).then(({ value }) => {
        const id = row.id
        const pas = value
        const data = { id, pas }
        updatePassWord(data).then(response => {
          this.$message({
            type: 'success',
            message: '新密码是: ' + value
          })
        })
      }).catch(() => {})
    },
    // 新增or修改操作
    submitFrom() {
      this.$refs.formInfo.validate(valid => {
        if (valid) {
          if (this.insertOrEdit) {
            // 修改操作
            userSave(this.form).then(response => {
              if (this.insertOrEdit) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: '新增成功,初始密码:123456'
                })
              }
              this.dialogFormInsertUpdate = false
              this.getUserInfo()
            })
          }
        } else {
          return false
        }
      })
    },
    // 删除操作
    delUserInfo(row) {
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delUserInfo(row)
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getUserInfo()
      }).catch(() => {})
    },
    // 更新状态
    switchStatus(row) {
      const statusText = row.status === 0 ? '启用' : '停用'
      this.$confirm('确定要' + statusText + row.userName + '用户吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return editUserStatus(row)
      }).then(() => {
        this.$message({
          type: 'success',
          message: '启用成功'
        })
      }).catch(() => {
        row.status = row.status === 0 ? 1 : 0
      })
    }
  }
})
</script>
